<?php

namespace App\Services;

use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\SystemSetting;
use App\Models\UserCoupon;
use App\Services\CouponService;
use Illuminate\Support\Facades\Log;

/**
 * 价格计算服务
 * 
 * 负责处理订单价格相关的所有计算逻辑，包括：
 * - 商品价格计算
 * - 运费计算
 * - 优惠券折扣计算
 * - 订单总价计算
 * 
 * @package App\Services
 * @author AI Assistant
 * @version 1.0.0
 */
class PriceCalculationService
{
    protected $couponService;

    public function __construct(CouponService $couponService)
    {
        $this->couponService = $couponService;
    }

    /**
     * 计算立即购买订单价格
     *
     * @param array $buyNowItem 立即购买商品信息
     * @param int|null $userCouponId 用户优惠券ID
     * @return array 计算结果
     */
    public function calculateBuyNowPrice(array $buyNowItem, ?int $userCouponId = null): array
    {
        try {
            // 验证商品
            $product = Product::find($buyNowItem['product_id']);
            
            if (!$product || !$product->is_active) {
                return [
                    'success' => false,
                    'message' => '商品不存在或已下架'
                ];
            }

            // 计算商品价格
            $price = $product->price;
            if (isset($buyNowItem['variant_id']) && $buyNowItem['variant_id']) {
                $variant = ProductVariant::find($buyNowItem['variant_id']);
                if ($variant && $variant->is_active) {
                    $price = $variant->price;
                }
            }

            $quantity = max(1, min(99, $buyNowItem['quantity']));
            $subtotal = $price * $quantity;

            // 计算运费
            $shipping = $this->calculateShipping($subtotal);

            // 计算优惠券折扣
            $couponDiscount = 0;
            if ($userCouponId) {
                $couponResult = $this->calculateCouponDiscount($userCouponId, $subtotal, [$buyNowItem]);
                if ($couponResult['success']) {
                    $couponDiscount = $couponResult['discount'];
                }
            }

            $total = $subtotal + $shipping - $couponDiscount;

            return [
                'success' => true,
                'data' => [
                    'subtotal' => $subtotal,
                    'shipping_fee' => $shipping,
                    'discount_amount' => 0,
                    'tax_amount' => 0,
                    'coupon_discount' => $couponDiscount,
                    'total_amount' => max(0, $total)
                ]
            ];

        } catch (\Exception $e) {
            Log::error('Buy now price calculation failed', [
                'buy_now_item' => $buyNowItem,
                'user_coupon_id' => $userCouponId,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'message' => '价格计算失败'
            ];
        }
    }

    /**
     * 计算购物车订单价格
     *
     * @param array $cartItems 购物车商品列表
     * @param int|null $userCouponId 用户优惠券ID
     * @return array 计算结果
     */
    public function calculateCartPrice(array $cartItems, ?int $userCouponId = null): array
    {
        try {
            $validItems = [];
            $subtotal = 0;

            // 验证每个商品
            foreach ($cartItems as $item) {
                $product = Product::find($item['product_id']);
                if (!$product || !$product->is_active) {
                    continue;
                }

                $price = $product->price;
                if (isset($item['variant_id']) && $item['variant_id']) {
                    $variant = ProductVariant::find($item['variant_id']);
                    if ($variant && $variant->is_active) {
                        $price = $variant->price;
                    }
                }

                $quantity = max(1, min(99, $item['quantity']));
                $itemSubtotal = $price * $quantity;

                $validItems[] = [
                    'product_id' => $product->id,
                    'variant_id' => $item['variant_id'] ?? null,
                    'name' => $product->name,
                    'price' => $price,
                    'quantity' => $quantity,
                    'subtotal' => $itemSubtotal
                ];

                $subtotal += $itemSubtotal;
            }

            if (empty($validItems)) {
                return [
                    'success' => false,
                    'message' => '没有有效的商品'
                ];
            }

            // 计算运费
            $shipping = $this->calculateShipping($subtotal);

            // 计算优惠券折扣
            $couponDiscount = 0;
            if ($userCouponId) {
                $couponResult = $this->calculateCouponDiscount($userCouponId, $subtotal, $validItems);
                if ($couponResult['success']) {
                    $couponDiscount = $couponResult['discount'];
                }
            }

            $total = $subtotal + $shipping - $couponDiscount;

            return [
                'success' => true,
                'data' => [
                    'subtotal' => $subtotal,
                    'shipping_fee' => $shipping,
                    'discount_amount' => 0,
                    'tax_amount' => 0,
                    'coupon_discount' => $couponDiscount,
                    'total_amount' => max(0, $total)
                ]
            ];

        } catch (\Exception $e) {
            Log::error('Cart price calculation failed', [
                'cart_items' => $cartItems,
                'user_coupon_id' => $userCouponId,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'message' => '价格计算失败'
            ];
        }
    }

    /**
     * 计算运费
     *
     * @param float $subtotal 商品小计
     * @return float 运费
     */
    protected function calculateShipping(float $subtotal): float
    {
        // 从系统设置读取运费配置
        $shippingFee = (float) SystemSetting::get('default_shipping_fee', 50);
        $freeThreshold = (float) SystemSetting::get('free_shipping_threshold', 1000);
        
        return $subtotal >= $freeThreshold ? 0 : $shippingFee;
    }

    /**
     * 计算优惠券折扣
     *
     * @param int $userCouponId 用户优惠券ID
     * @param float $orderAmount 订单金额
     * @param array $items 商品列表
     * @return array 计算结果
     */
    protected function calculateCouponDiscount(int $userCouponId, float $orderAmount, array $items): array
    {
        try {
            // 验证优惠券是否属于当前用户
            $userCoupon = UserCoupon::where('id', $userCouponId)
                ->where('user_id', auth()->id())
                ->where('status', 'unused')
                ->first();

            if (!$userCoupon) {
                return [
                    'success' => false,
                    'message' => '优惠券不存在或已使用'
                ];
            }

            return $this->couponService->calculateDiscount($userCouponId, $orderAmount, $items);

        } catch (\Exception $e) {
            Log::error('Coupon discount calculation failed', [
                'user_coupon_id' => $userCouponId,
                'order_amount' => $orderAmount,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'message' => '优惠券计算失败'
            ];
        }
    }
}
